package com.mwj.auction.Aspect;

import com.mwj.auction.exception.SystemException;
import com.mwj.auction.utils.jwtUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 马文杰
 * @version 1.0
 */

@Aspect
@Service
public class TokenAspect {
    @Autowired
//    private RedisTemplate redisTemplate;
    private static  ThreadLocal<String> tokenHolder = new ThreadLocal<>();

    //如果需要websocket则开启某个文件,屏蔽webSocket的token验证
    //    @Before("execution(* com.mwj.auction.controller..*(..)) " +
    //            "&& (!within(com.mwj.auction.controller.ChatEndpoint) " +
    //            "&& !within(com.mwj.auction.controller.WebRtcWSServer))"+
    //            "&& !within(com.mwj.auction.controller.CrowdSocket)")

    @Before("execution(* com.mwj.auction.controller.*.*(..))")
    public void beforeControllerMethod(JoinPoint joinPoint) throws SystemException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //获取访问接口地址
        String url = request.getRequestURI();
        //如果出现以上的接口地址，就不需要token
        List<String> urlList = new ArrayList<>();
//        urlList.add("/user/**");
          urlList.add("/user/login");
          urlList.add("/user/reg");
          urlList.add("/user/adminLogin");
          urlList.add("/upload/uploadFile");
        // 如果出现以上的接口地址，就不需要token,数组中的/**就代表所有子路径
        for (String pattern : urlList) {
            if (url.startsWith(pattern.replace("**", ""))) {
                return;
            }
        }

        String token = request.getHeader("Token");
        String userid = jwtUtils.parseToken(token);
        if (userid==null){
            //token解析失败,用户未登录，报异常，并且异常返回给前端
            throw new SystemException();
        }
//        String o = (String) redisTemplate.opsForValue().get(userid);
//        if (o==null){
//            //token不存在,用户未登录，报异常，并且异常返回给前端
//            throw new SystemException();
//        }
//        if (userid.equals(jwtUtils.parseToken(o))){
//            tokenHolder.set(userid);
//            return;
//        }
        tokenHolder.set(userid);
        return;
//        throw new SystemException();
    }

    public static String getToken() {
        return tokenHolder.get();
    }
}
